#!/usr/bin/env python3
# vim:fileencoding=utf-8

import os, sys
from subprocess import getoutput
from wingdns import WingDNS, WingDNSError
from getpass import getpass

cookiefile = os.path.expanduser('~/scripts/python/pydata/wingdns.cookie')

def updateA():
  w = WingDNS(cookiefile)
  try:
    w.getAdminConsole('46395')
  except WingDNSError:
    if sys.stdin.isatty():
      w.login('lily', getpass())
      w.getAdminConsole('46395')
    else:
      print('WingDNS: 请登录', file=sys.stderr)
      sys.exit(1)

  r = [x for x in w.records['A'] if x['host'] == '@']
  if r:
    r = r[0]
    r['data'] = getoutput('myip')
    w.modi(r)
  else:
    w.add({
      'type': 'A',
      'host': '@',
      'data': getoutput('myip'),
      'mx': '',
    })

if __name__ == '__main__':
  updateA()
